package com.haonan.springboot_exercise.netty.client;

import com.alibaba.fastjson.JSONObject;
import com.haonan.springboot_exercise.bean.pojo.MsgResult;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author haonan
 * @date 2021/4/17 19:01
 **/
@Slf4j
public class PopClientHandler extends ChannelInboundHandlerAdapter {
    private ChannelHandlerContext ctx;
    private MsgResult msgResultFromServer;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端Active .....");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("客户端收到消息: {}", msg.toString());
        String msgResultStr = msg.toString();
        msgResultFromServer = JSONObject.parseObject(msgResultStr,MsgResult.class);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    public void sendDataToServer(Channel channel, Object msg) throws Exception{
        channel.writeAndFlush(msg);
        log.info("客户端发送消息: {}", msg.toString());
    }

    public void setCtx(ChannelHandlerContext ctx){
        this.ctx = ctx;
    }

    public ChannelHandlerContext getCtx(){
        return ctx;
    }

    public MsgResult getMsgResultFromServer() throws InterruptedException {
        // 加这一步循环主要是为了确保能返回msgResult，不然时间太快，可能返回一个空值
        while (msgResultFromServer == null){
            Thread.sleep(5);
        }
        return msgResultFromServer;
    }

}